/**
 * 用户认证相关API
 */
import request from '@/utils/request'
import type { ApiResponse } from './types/common'
import type {
  LoginParams,
  RegisterParams,
  LoginResponse,
  User
} from '@/types/user'

/**
 * 用户登录/注册
 */
export const checkIn = (params: LoginParams | RegisterParams): Promise<ApiResponse<LoginResponse>> => {
  return request.post('/user/checkIn', params)
}

/**
 * 用户登出
 */
export const logout = (refreshToken?: string): Promise<ApiResponse<null>> => {
  return request.post('/user/logout', { refreshToken })
}

/**
 * 获取用户登录配置信息
 */
export const getLoginConfig = (): Promise<ApiResponse<{
  userLoginCaptchaSwitch: boolean
  accountVerificationType: string[]
}>> => {
  return request.get('/user/checkIn')
}

/**
 * 获取验证码图片
 */
export const getCaptcha = (captchaId: string): Promise<ApiResponse<{
  captcha: string
  captchaId: string
}>> => {
  return request.get('/common/captcha', {
    params: { id: captchaId }
  })
}

/**
 * 获取点击验证码
 */
export const getClickCaptcha = (captchaId: string): Promise<ApiResponse<{
  id: string
  base64: string
  text: string[]
  width: number
  height: number
}>> => {
  return request.get('/common/clickCaptcha', {
    params: { id: captchaId }
  })
}

/**
 * 验证点击验证码
 */
export const checkClickCaptcha = (params: {
  id: string
  info: string
  unset: boolean
}): Promise<ApiResponse<null>> => {
  return request.post('/common/checkClickCaptcha', params)
}

/**
 * 发送邮箱验证码
 */
export const sendEmailCode = (
  email: string,
  event: string,
  captchaInfo?: { captchaId: string; captchaInfo: string }
): Promise<ApiResponse<null>> => {
  const requestData = {
    email,
    event,
    ...captchaInfo
  }
  console.log('发送邮箱验证码请求数据:', requestData)

  return request.post('/ems/send', requestData).then(response => {
    console.log('发送邮箱验证码响应:', response)
    return response
  }).catch(error => {
    console.error('发送邮箱验证码请求失败:', error)
    throw error
  })
}



/**
 * 检查用户名是否可用
 */
export const checkUsername = (username: string): Promise<ApiResponse<{ available: boolean }>> => {
  return request.get('/user/checkUsername', {
    params: { username }
  })
}

/**
 * 检查邮箱是否可用
 */
export const checkEmail = (email: string): Promise<ApiResponse<{ available: boolean }>> => {
  return request.get('/user/checkEmail', {
    params: { email }
  })
}



/**
 * 刷新Token
 */
export const refreshToken = (refreshToken: string): Promise<ApiResponse<{
  token: string
  refreshToken: string
}>> => {
  return request.post('/user/refreshToken', { refreshToken })
}

/**
 * 获取当前用户信息
 */
export const getCurrentUser = (): Promise<ApiResponse<User>> => {
  return request.get('/user/info')
}
